﻿using Microsoft.Extensions.FileProviders;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Mrc.Config
{
    public class JsonConfigFileProvider : IJsonConfigFileProvider
    {

        private IFileProvider _fileProvider=new PhysicalFileProvider(AppContext.BaseDirectory ?? string.Empty);

        private Dictionary<string, IFileInfo> _fileInfos= new Dictionary<string, IFileInfo>(StringComparer.OrdinalIgnoreCase);

        public JsonConfigFileProvider() { }

        public JsonConfigFileProvider(ConfigFileInfo configFileInfo) => Add(configFileInfo);

        public JsonConfigFileProvider(List<ConfigFileInfo> configFileInfos) => Add(configFileInfos);
 
        public void Add(ConfigFileInfo configFileInfo)
        {
            if (_fileInfos.ContainsKey(configFileInfo.Name))
            {
                _fileInfos[configFileInfo.Name] = _fileProvider.GetFileInfo(configFileInfo.Path);
            }
            else
            {
                _fileInfos.Add(configFileInfo.Name, _fileProvider.GetFileInfo(configFileInfo.Path));
            }
        }

        public void Add(List<ConfigFileInfo> configFileInfos)
        {
            configFileInfos.ForEach(item => Add(item));
        }

        public IFileInfo GetFileInfo(string Name)
        {
            if (_fileInfos.ContainsKey(Name)) return _fileInfos[Name];
            throw new ArgumentNullException("不存在配置信息");
        }
        public List<IFileInfo> GetFileInfo(List<string> Names)
        {
            List<IFileInfo> results = new List<IFileInfo>();
            Names.ForEach((item) => {
                results.Add(GetFileInfo(item));
            });
            return results;
        }

        public List<IFileInfo> GetAllFileInfo()
        {
            return _fileInfos.Values.ToList();
        }

        public Stream GetStream(string Name)
        {
            if (_fileInfos.ContainsKey(Name)) return _fileInfos[Name].CreateReadStream();
            throw new ArgumentNullException("不存在配置信息");
        }

        public List<Stream> GetStreams(List<string> Names)
        {
            List<Stream> results = new List<Stream>();
            Names.ForEach((item) => {
                results.Add(GetFileInfo(item).CreateReadStream());
            });
            return results;
        }
        public List<Stream> GetAllStreams()
        {
          return  _fileInfos.Values.ToList().Select(x => x.CreateReadStream()).ToList();
        }

    }
}
